package com.hellprototypes.hellwatch.assistant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class HW_Assistant extends Activity {
    private final static int REQUEST_ENABLE_BT = 1;
    private final static int REQUEST_ENABLE_GPS = 2;
    private final static String TAG = "HellWatch-Activity";

    // UI elements
    private TextView mMessages;
    private ScrollView mScrollView;
    private TextView mTextView;

    private AssistantReceiver mAssistantReceiver;

    // OnCreate, called once to initialize the activity.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hw_assistant);

        mMessages = (TextView) findViewById(R.id.messages);
        mScrollView = (ScrollView) findViewById(R.id.scrollView);
        mTextView = (TextView) findViewById(R.id.stepMessage);

        Log.d(TAG, "# onCreate()");
    }

    @Override
    public void onStart(){
        mAssistantReceiver = new AssistantReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Common.HWA_ACTION);
        registerReceiver(mAssistantReceiver, filter);
/*
        LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (!alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, REQUEST_ENABLE_GPS);
        }
*/
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            noteMessage("Bluetooth LE not supported on this device");
        } else {
            SendCommandToService(Common.SERVICE_CMD_INIT);
        }
        Log.d(TAG, "# onStart()");
        super.onStart();
    }

    // OnResume, called right before UI is displayed.  Start the BTLE connection.
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "# onResume()");
    }

    // OnStop, called right before the activity loses foreground focus.  Close the BTLE connection.
    @Override
    protected void onStop() {
        unregisterReceiver(mAssistantReceiver);
        super.onStop();
        Log.d(TAG, "# onStop()");
    }

    @Override
    public void onBackPressed() {
        Intent intent= new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    //noteMessage("Enable Bluetooth enable allowed");
                    SendCommandToService(Common.SERVICE_CMD_START_SCAN);
                } else {
                    //noteMessage("Bluetooth not enable");
                    stopServiceThenFinish();
                }
                break;
            case REQUEST_ENABLE_GPS:
                //do nothing
                break;
        }
    }

    public class AssistantReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(Common.HWA_ACTION)) {
                Bundle bundle = intent.getExtras();
                if(bundle.containsKey(Common.BUNDLE_KEY_NAME_MSG)) {
                    String msg = bundle.getString(Common.BUNDLE_KEY_NAME_MSG);
                    noteMessage(msg);
                } else
                if(bundle.containsKey(Common.BUNDLE_KEY_NAME_CMD)) {
                    switch (bundle.getInt(Common.BUNDLE_KEY_NAME_CMD)) {
                        case Common.SERVICE_CMD_REQ_EN_BT:
                            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                            Log.d(TAG, "# AssistantReceiver: SERVICE_CMD_REQ_EN_BT");
                            break;
                        default:
                            Log.d(TAG, "# AssistantReceiver: unknown cmd");
                            break;
                    }
                } else
                if(bundle.containsKey(Common.BUNDLE_KEY_NAME_STEP)) {
                    String data = bundle.getString(Common.BUNDLE_KEY_NAME_STEP);
                    mTextView.setText(data);
                } else
                if(bundle.containsKey(Common.BUNDLE_KEY_NAME_NOTE)) {
                    String data = bundle.getString(Common.BUNDLE_KEY_NAME_NOTE);
                    noteMessage("> Hell Watch Note: [ " + data + " ]");
                }
            }
        }
    }

    public void stopServiceThenFinish() {
        Intent serviceIntent = new Intent(this, AssistantService.class);
        stopService(serviceIntent);
        this.finish();
    }

    public void SendCommandToService(int command) {
        Intent serviceIntent = new Intent(this, AssistantService.class);
        Bundle bundle = new Bundle();
        bundle.putInt(Common.BUNDLE_KEY_NAME_CMD, command);
        serviceIntent.putExtras(bundle);
        startService(serviceIntent);
    }

    private void noteMessage(final CharSequence text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMessages.append(text);
                mMessages.append("\n");
                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    public void on_bt_launch_IR_Ctrl_clicked(View view){
        Intent intent = new Intent(this, IR_RemoteControl.class);
        startActivity(intent);
    }

    // Boilerplate code from the activity creation:
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.hw_assistant, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_exit) {
            AlertDialog builder = new AlertDialog.Builder(this)
                    .setIconAttribute(android.R.attr.alertDialogIcon)
                    .setTitle("Exit Confirm")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            stopServiceThenFinish();
                        }
                    })
                    .setNegativeButton("No", null)
                    .show();
            return true;
            /*final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        adapter = bluetoothManager.getAdapter();*/
        }
        if (id == R.id.action_beep) {
            SendCommandToService(Common.SERVICE_CMD_BEEP);
            return true;
        }
        if (id == R.id.action_clear) {
            mMessages.setText("");
            return true;
        }

        if (id == R.id.action_heart_rate) {
            Intent intent = new Intent(this, HeartRateMonitor.class);
            startActivity(intent);
            return true;
        }
        if (id == R.id.action_ir_remote) {
            Intent intent = new Intent(this, IR_RemoteControl.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
